﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Headlight.CustomValidators
{
    public class AgeValidationRule : ModelClientValidationRule
    {
        public AgeValidationRule(int minAge, string errorMessage)
        {
            ErrorMessage = errorMessage;
            ValidationType = "age";
            ValidationParameters.Add("minage", minAge);
        }


    }

    public class AgeAttribute : ValidationAttribute, IClientValidatable
    {
        public int MinAge { get; set; }

        public AgeAttribute()
        {
            MinAge = 18;
        }

        public AgeAttribute(int maxAge)
        {
            MinAge = maxAge;
        }

        public override bool IsValid(object value)
        {
            if (value == null) return true;

            int age = (int)value;

            if (age <= this.MinAge)
                return false;

            return true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new AgeValidationRule(this.MinAge, ErrorMessage);
        }
    }
}